<?php

namespace app\api\controller\zsdl;
use app\common\controller\Api;

use think\Db;
use think\cache;
use think\Log;
use wxutils\index as WxUtils;

use app\admin\model\User as UserModel;
use app\admin\model\zs\dl\User as ZsdlUserModel;
use app\admin\model\zs\dl\Frend as ZsdlFrendModel;
use app\admin\model\zs\dl\Prize as PrizeModel;
use app\admin\model\zs\dl\Prizerecord as PrizerecordModel;





// 正商点亮项目
class Index extends Api
{

    protected $noNeedLogin = ['login','testlogin','dayClear'];
    protected $noNeedRight = ['*'];


    private $appid = 'wx685b6dd0fdef3f36';
    private $secret = 'a0b6391ec5ec0c9a62b18649ae0c63cd';

    private $openidPre = 'zsdl_';
    private $dayClearCode = 'zsdl_day_clear';

    
    // 获取用户列表
    public function login()
    {

        $code = $this->request->param('code');
        $wxUserInfo = WxUtils::getWxUserInfo($this->appid, $this->secret, $code);

        if(!isset($wxUserInfo,$wxUserInfo['openid'])){
            $this->error(__('获取微信信息失败'));
        }

        $data = $this->loginInternal($wxUserInfo);
        
        $this->success(__('登录成功'), $data);
    }
    // 测试登录
    public function testlogin(){
        $wxUserInfo = [
            "openid" => $this->request->param('openid'),
            "nickname" => $this->request->param('nickname'),
        ];

        $data = $this->loginInternal($wxUserInfo);
        $this->success(__('登录成功'), $data);
    }

    // 检查当前用户是否可以抽奖
    public function checkPrize(){
        $userid = $this->auth->id;
        
        $userModel = new ZsdlUserModel();
        $user = $userModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在');
        }

        $lightNum = $user['lightNum'] + $user['videoNum'];

        if($lightNum < 8){
            $this->error('您还没有点亮全部地标，无法抽奖');
        }

        // 判断是否填写过信息
        if($user['name'] == '' || $user['tel'] == ''){
            $this->success('您还没有填写信息',['status' => 0]);
        }

        // 判断是否已经抽过奖了
        $prizeRecordModel = new PrizerecordModel();
        $prizeRecord = $prizeRecordModel->where('openid', $user->openid)->find();
        if($prizeRecord){
            $this->success('您已经抽过奖了',['status' => 2]);
        }
        // status 0需要填写信息 1可以抽奖  2抽奖次数已用完
        $this->success('您可以抽奖了',['status' => 1]);
    }

    // 保存用户信息
    public function saveUserInfo(){
        $userid = $this->auth->id;
        $userModel = new ZsdlUserModel();
        $user = $userModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在');
        }
        $name = $this->request->param('name');
        $tel = $this->request->param('tel');
        $user->name = $name;
        $user->tel = $tel;
        $user->save();
        $this->success('提交成功');
    }


    // 添加好友记录
    private function addFrendRecord($fid,$uid){
        // 查询是否已经添加过
        $zsdlFrendModel = new ZsdlFrendModel();
        $zsdlFrend = $zsdlFrendModel->where('fid',$fid)->where('uid',$uid)->find();
        if(!$zsdlFrend){
            $zsdlFrendModel = new ZsdlFrendModel();
            $zsdlFrendModel->fid = $fid;
            $zsdlFrendModel->uid = $uid;
            $zsdlFrendModel->save();
            return true;
        }
        return false;
    }

    // 点亮
    private function light($uid){
        $zsdlUserModel = new ZsdlUserModel();
        $zsdlUser = $zsdlUserModel->where('user_id', $uid)->find();
        if($zsdlUser && $zsdlUser['lightNum'] < 5){
            $zsdlUser->lightNum++;
            $zsdlUser->save();

            if($zsdlUser['lightNum'] <= 4){
                $prize = $this->getPrizeInternalLight(0);
                if($prize){
                    $user = $zsdlUserModel->where('user_id', $uid)->find();
                    // 开启事务，插入中奖记录，更新用户状态
                    try {
                        Db::startTrans();
                        $recordModel = new PrizerecordModel();
                        $addData = [
                            "prize_id" => $prize["prizeId"],
                            "openid" => $user->openid,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                        // 插入中奖记录
                        $recordModel->insertGetId($addData);
                        Log::record('点亮抽奖'.$user->openid.'点亮抽奖'.$prize);
                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error('抽奖失败'.$e->getMessage());
                    }
                }
            }

        }
      
    }

    // 抽奖
    public function getPrize()
    {
        $userid = $this->auth->id;
        $zsdlUserModel = new ZsdlUserModel();
        $user = $zsdlUserModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在1');
        }
        //判断是否有机会
        $isHavsPrizeNum = $this->checkUserIsHavsPrizeNum($userid);
        if(!$isHavsPrizeNum){
            $this->error('您没有抽奖机会了');
        }

        $status = 0;
        $prize = $this->getPrizeInternal($status);

        if($prize)
        {
            // 开启事务，插入中奖记录，更新用户状态
            try {
                Db::startTrans();
                $recordModel = new PrizerecordModel();
                $addData = [
                    "prize_id" => $prize["prizeId"],
                    "openid" => $user->openid,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                // 插入中奖记录
                $add_res = $recordModel->insertGetId($addData);
                if($add_res)
                {
                    $return_data = [
                        "prize_id" => $add_res,
                        "prizeId" => $prize["prizeId"],
                        "name" => $prize["name"],
                        "frameIndex" => $prize["frameIndex"],
                        "type" => $prize["type"],
                        "url" => $prize["url"]
                    ];
                }
                // 抽奖后更新用户状态
                $this->prizeAfter($userid, $prize);
               
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('抽奖失败'.$e->getMessage());
            }
        }else{
            $this->error('奖品已经发送完毕');
        }
        $this->success('请求成功',$return_data);
    }

    // 获取中奖记录
    public function getPrizeList(){
        $userid = $this->auth->id;
        $userModel = new ZsdlUserModel();
        $user = $userModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在');
        }
        $prizeRecordModel = new PrizerecordModel();
        $prizeRecord = $prizeRecordModel::with('prize')->where('openid', $user->openid)->select();
        if(empty($prizeRecord)){
            $this->error('还未获得任何奖品');
        }else{
            $this->success('请求成功',$prizeRecord);
        }
    }


    // 看视频点亮
    public function watchVideoLight(){
        $userid = $this->auth->id;
        $userModel = new ZsdlUserModel();
        $user = $userModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在');
        }
        $key = $this->openidPre . $user->openid;
        $lightNum = cache::get($key);
        if($lightNum >= 3){
            $this->error('视频激励次数已用完');
        }
        cache::inc($key,1);
        $user->videoNum++;
        $user->save();
        $this->success('请求成功');
    }


    // 获取最新点量状态
    public function getLightNum(){
        $userid = $this->auth->id;
        $userModel = new ZsdlUserModel();
        $user = $userModel->field('lightNum,videoNum')->where('user_id', $userid)->find();
        $lightNum = $user['lightNum'] + $user['videoNum'];
        $this->success('请求成功',$lightNum);
    }


    // 日清
    public function dayClear(){
        // 奖品当日发放数量清零
        $code = $this->request->param('code');
        if (!$code || $code != $this->dayClearCode) {
            $this->error('请登录');
        }
        $prizeModel = new PrizeModel();
        $prizeModel->where('dayNum','>',0)->update(['dayNum' => 0]);
        $this->success('请求成功');
   }




    // 检查用户是否还有抽奖机会
    private function checkUserIsHavsPrizeNum($userid){
        $userModel = new ZsdlUserModel();
        $user = $userModel->where('user_id', $userid)->find();
        if(!$user){
            $this->error('用户不存在');
        }

        $lightNum = $user['lightNum'] + $user['videoNum'];
        if($lightNum < 8){
            $this->error('您还没有点亮全部地标，无法抽奖');
        }

        // 判断是否已经抽过奖了
        $prizeRecordModel = new PrizerecordModel();
        $prizeRecord = $prizeRecordModel->where('openid', $user->openid)
        ->where("prize_id","<>", "jiangchi-xiaolongxia")
        ->where("prize_id","<>", "jiangchi-pijiu")
        ->find();
        if($prizeRecord){
            $this->error('您已经抽过奖了');
        }
        return true;
    }

    // 抽奖后钩子
    private function prizeAfter($userid,$prize){
        // 本项目无需更新用户状态
        Log::record('抽奖后钩子'.$userid.'抽奖后钩子'.$prize);
    }

    private function getPrizeInternal($status)
    {
        $configModel = new PrizeModel();
        $cards = $configModel->where("ratio",">","0")->where('type','0')->select();
        $_cards = [];
        $endNum   = 0;
        foreach ($cards as $k => $v) {
            //总库存 和 单日限量控制
            if($v['totalNum'] > $v['num'] && $v['dayTotalNum'] > $v['dayNum'])
            {
            	if($status == 1)
            	{
            		// 虚拟 实物 都可以
        			$cards[$k]['startNum'] = $endNum;
	                $endNum = $endNum + $v['ratio2']; //该奖品权重
	                $cards[$k]['endNum'] = $endNum;
	                array_push($_cards,$cards[$k]);

            	}else{
            		// 虚拟 实物 都可以
        			$cards[$k]['startNum'] = $endNum;
	                $endNum = $endNum + $v['ratio']; //该奖品权重
	                $cards[$k]['endNum'] = $endNum;
	                array_push($_cards,$cards[$k]);
            	}
            }

        }

        if(empty($_cards)) return false;

        $randNum = rand(0,$endNum);
        $card = [];

        //根据权重 取出奖品
        foreach ($_cards as $k => $v) {
            if($v['startNum'] <= $randNum && $v['endNum'] >= $randNum)
            {
                $card = $_cards[$k];
            }
        }

        if(!empty($card)){ //更新数据库  card表  用户表
            // 更新数据库
            $cardUpdateRes = $configModel->where("prizeId","=",$card["prizeId"])->inc('num')->inc('dayNum')->update();
            if($cardUpdateRes){
               return $card;
            }
        }
        return false;
    }
    

    private function getPrizeInternalLight($status)
    {
        $configModel = new PrizeModel();
        $cards = $configModel->where("ratio",">","0")->where('type','1')->select();
        $_cards = [];
        $endNum   = 0;
        foreach ($cards as $k => $v) {
            //总库存 和 单日限量控制
            if($v['totalNum'] > $v['num'] && $v['dayTotalNum'] > $v['dayNum'])
            {
            	if($status == 1)
            	{
            		// 虚拟 实物 都可以
        			$cards[$k]['startNum'] = $endNum;
	                $endNum = $endNum + $v['ratio2']; //该奖品权重
	                $cards[$k]['endNum'] = $endNum;
	                array_push($_cards,$cards[$k]);

            	}else{
            		// 虚拟 实物 都可以
        			$cards[$k]['startNum'] = $endNum;
	                $endNum = $endNum + $v['ratio']; //该奖品权重
	                $cards[$k]['endNum'] = $endNum;
	                array_push($_cards,$cards[$k]);
            	}
            }

        }

        if(empty($_cards)) return false;

        $randNum = rand(0,$endNum);
        $card = [];

        //根据权重 取出奖品
        foreach ($_cards as $k => $v) {
            if($v['startNum'] <= $randNum && $v['endNum'] >= $randNum)
            {
                $card = $_cards[$k];
            }
        }

        if(!empty($card)){ //更新数据库  card表  用户表
            // 更新数据库
            $cardUpdateRes = $configModel->where("prizeId","=",$card["prizeId"])->inc('num')->inc('dayNum')->update();
            if($cardUpdateRes){
               return $card;
            }
        }
        return false;
    }

    private function loginInternal($wxUserInfo){
        $userModel = new userModel();
        // 截取前15位
        $username = $this->openidPre . substr($wxUserInfo["openid"], 0, 15);
        $user = $userModel->where('username', $username)->find();
        $zsdlUserModel = new ZsdlUserModel();
        $isNewUser = false;
        // 如果用户不存在，则创建用户
        if(!$user){
            $password = md5($username);
            $email = $username . '@qq.com';
            $ret = $this->auth->register($username, $password, $email, '', []);
            if(!$ret){
                $this->error($this->auth->getError());
            }

            $user = $this->auth->getUser();
            // 创建本表项目表
            $zsdlUserModel->user_id = $user->id;
            $zsdlUserModel->openid = $wxUserInfo["openid"];
            $zsdlUserModel->avatar = $wxUserInfo["headimgurl"] ?? '';
            $zsdlUserModel->nickname = $wxUserInfo["nickname"] ?? '';
            $zsdlUserModel->videoNum = 0;
            $zsdlUserModel->lightNum = 0;
            $zsdlUserModel->save();
            $isNewUser = true;

           
        }

        // 如果是新用户，并且携带fid参数
        $fid = $this->request->param('fid');
        if($fid){
            $isNewFrend = $this->addFrendRecord($fid,$user->id);
            if($isNewFrend){
                $light_ratio = config('site.light_ratio');
                 // 概率
                $randNum = rand(0,100);
                if($randNum < $light_ratio){
                    $this->light($fid);
                }
            }
         }

        $ret = $this->auth->direct($user->id);
        if(!$ret){
            $this->error($this->auth->getError());
        }

        $zsdlUser = $zsdlUserModel->where('user_id', $user->id)->find();

        return [
            'userinfo' => $this->auth->getUserinfo(),
            'zsdlUser' => $zsdlUser,
            'isNewUser' => $isNewUser
        ];
    }
}
